package com.meixiang.activity.rongcloud;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.meixiang.R;
import com.meixiang.dialog.AlertDialogFragment;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.MXApplication;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.TitleView;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 作者：黑哥 on 2016/6/13 11:22
 * <p/>
 * 融云 会话页面
 */
public class ConversationActivity extends FragmentActivity {
    @Bind(R.id.title)
    TitleView mTitle;
    private RelativeLayout mBack;
    private String mTargetId;
    private String token;

    private Activity mActivity;
    /**
     * 刚刚创建完讨论组后获得讨论组的id 为targetIds，需要根据 为targetIds 获取 targetId
     */
    private String mTargetIds;

    /**
     * 会话类型
     */
    private Conversation.ConversationType mConversationType;


    private boolean isOverdue=false;


    private static final int REQUEST_PERMISSION = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.conversation);
        ButterKnife.bind(this);
        mActivity=ConversationActivity.this;

        getToken();
        Intent intent = getIntent();
        initTitle();
        /**
         * 获取token
         * 建立与融云连接
         * */
        getIntentDate(intent);
        isReconnect(intent);
        PackageManager pkgManager = getPackageManager();

        //第一步 检测是否注册过权限  PackageManager.PERMISSION_GRANTED注册过了
        boolean cameraPermissions=ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT>=23||!cameraPermissions) {
            requestPermission();
        }


    }

    private void initTitle() {
        mTitle.setTitle("客服");
        mTitle.setLeftImageButton(R.mipmap.back);
        mTitle.showLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
    private void requestPermission() {

        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.RECORD_AUDIO},
                REQUEST_PERMISSION);
    }
    /**
     * 展示如何从 Intent 中得到 融云会话页面传递的 Uri
     */
    private void getIntentDate(Intent intent) {

        mTargetId = intent.getData().getQueryParameter("targetId");
        mTargetIds = intent.getData().getQueryParameter("targetIds");
        //intent.getData().getLastPathSegment();//获得当前会话类型
        mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));

        enterFragment(mConversationType, mTargetId);
//        setActionBarTitle(mTargetId);
    }

    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType
     * @param mTargetId
     */
    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();

        fragment.setUri(uri);
    }


    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect(Intent intent) {


        String token = null;

        if (DemoContext.getInstance() != null) {
            token = MXApplication.mApp.getSession().get("token");
            /**
             * 链接融云判断当前的token 是否过期
             * 如果过期 重新获取token
             * */
            connect(token);

        }



        //push或通知过来
        if (intent != null && intent.getData() != null && intent.getData().getScheme().equals("rong")) {

            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("push") != null
                    && intent.getData().getQueryParameter("push").equals("true")) {

                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if(RongIM.getInstance()==null||RongIM.getInstance().getRongIMClient()==null){
                    reconnect(token);
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            }
        }
    }
//    /**
//     * 重连
//     *
//     * @param token
//     */   if (!MXApplication.mApp.hasLogin()&&!v.equals(ivShopping)&&!v.equals(linearStaging)){
//        startActivity(LoginActivity.class);
//        return;
//    }

    private void reconnect(String token) {

        if (getApplicationInfo().packageName.equals(MXApplication.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {

                }


                @Override
                public void onSuccess(String s) {

                    enterFragment(mConversationType, mTargetId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });
        }
    }

    private void getToken() {
        HttpUtils.post(Config.RONGCLOUD_GET_TOKEN, null, new HttpCallBack(mActivity) {

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.e("TAG", "得到token=" + result.toString());
                token = result.optString("token");
                //
                // 存储token
                HashMap<String, String> vals = new HashMap<String, String>();
                vals.put("token",token);
                MXApplication.mApp.getSession().set(vals);
                Log.e("TAG", "得到token=====" + token);
                /**融云链接*/
                connect(token);
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(mActivity, message);
            }
        });
    }
    /**
     * 建立与融云服务器的连接
     *
     * @param token
     */
    private void connect(String token) {

        if (getApplicationInfo().packageName.equals(MXApplication.getCurProcessName(getApplicationContext()))) {

            /**
             * IMKit SDK调用第二步,建立与服务器的连接
             */
            RongIM.connect(token, new RongIMClient.ConnectCallback() {

                /**
                 * Token 错误，在线上环境下主要是因为 Token 已经过期，您需要向 App Server 重新请求一个新的 Token
                 */
                @Override
                public void onTokenIncorrect() {
                    Log.e("LoginActivity", "--onTokenIncorrect");
                    getToken();
                    //清空token
                }

                /**
                 * 连接融云成功
                 * @param userid 当前 token
                 */
                @Override
                public void onSuccess(String userid) {

                    Log.e("LoginActivity", "--onSuccess" + userid);
                }

                /**
                 * 连接融云失败
                 * @param errorCode 错误码，可到官网 查看错误码对应的注释
                 *                  http://www.rongcloud.cn/docs/android.html#常见错误码
                 */
                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                    Log.e("LoginActivity", "--onError" + errorCode);
                }
            });
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION :
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        Log.d("lw","权限选择了");
                    }else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {

                        }else{
                            new AlertDialogFragment.Builder()
                                    .setContentText("为了能够正常的语音聊天，请开启记录音频权限")
                                    .setLeftBtnText("取消")
                                    .setRightBtnText("手动授权")
                                    .setRightClickCallBack(new AlertDialogFragment.RightClickCallBack() {
                                        @Override
                                        public void dialogRightBtnClick() {
                                            Uri uri=Uri.parse("package:"+getPackageName());
                                            Intent intent=new Intent("android.settings.APPLICATION_DETAILS_SETTINGS", uri);
                                            startActivity(intent);
                                        }
                                    })
                                    .build()
                                    .show(getSupportFragmentManager(), AlertDialogFragment.TAG);
                        }
                    }
                }

        }

    }



}
